package org.example.myleet.p1302;

import org.example.myleet.Utils.TreeNode;

public class Solution {

    private int deepest = 0;

    private int sum = 0;

    public int deepestLeavesSum(TreeNode root) {
        deepest = 0;
        sum = 0;
        dfs(root, 1);
        return sum;
    }

    private void dfs(TreeNode node, int level) {
        if (level > deepest) {
            deepest = level;
            sum = node.val;
        } else if (level == deepest) {
            sum += node.val;
        }
        if (null != node.left) {
            dfs(node.left, level + 1);
        }
        if (null != node.right) {
            dfs(node.right, level + 1);
        }
    }
}
